package com.v1.video.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.v1.video.R;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.PlayerInfo;
import com.v1.video.domain.SearchUpdataFocousInfo;
import com.v1.video.domain.SearchUser2Obj;
import com.v1.video.domain.SearchUser2PageInfo;
import com.v1.video.domain.SearchVideo2ObjInator;
import com.v1.video.domain.SetHead;
import com.v1.video.option.util.SearchAboutUtil;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;

public class SearchMoreUserActivity extends BaseActivity implements OnClickListener {

	private PullToRefreshListView mContentLv;
	private ContentAdapter mContentAdapter;
	private ListView mContent;
	private List<PlayerInfo> mUserInfos = new ArrayList<PlayerInfo>();
	
	private final int STATE_REFRESH = 0;//刷新
	private final int STATE_DOWNLOAD = 1;//加载
	private int state = STATE_REFRESH;
	private String keyWord = "";
	private int pageSize = 20;
	private int pageIndex = 1;
	TextView titleTxt;
	private int flag = 0;
	private boolean isSetCount = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_more_comm_activity_lay);
	}

	@Override
	protected void initView() {
		Bundle bundle=this.getIntent().getExtras();
		((TextView)findViewById(R.id.tv_caption)).setText(R.string.search_more_header_title);
		flag = bundle.getInt("flag", 0);
		titleTxt=(TextView)findViewById(R.id.titleTxt);
		keyWord = bundle.getString("searchTxt");
//		String val=this.getResources().getString(
//				R.string.search_more_user_title,keyWord,
//				bundle.getInt("recordNum"));
//		Utility.ChangeTextViewPartWordsTextColor(titleTxt, val,
//				this.getResources().getColor(R.color.title_alpha_blue), 
//				bundle.getString("searchTxt"));
		String val=this.getResources().getString(
				R.string.search_more_user_title,keyWord,0);
		Utility.ChangeTextViewPartWordsTextColor(titleTxt, val,
				this.getResources().getColor(R.color.title_alpha_blue), 
				bundle.getString("searchTxt"));
		mContentLv = (PullToRefreshListView) findViewById(R.id.lv_content);
		mContentLv.setScrollingWhileRefreshingEnabled(false);
	}

	@Override
	protected void initData() {
		mContent = mContentLv.getRefreshableView();
		mContent.setBackgroundDrawable(null);
		mContentLv.setDividerDrawable(null);
		mContentLv.setBackgroundDrawable(null);
		mContentLv.setMode(Mode.BOTH);// 同时由下拉刷新和上啦加载更多
		// mContentLv.setMode(Mode.PULL_FROM_START);//只有下拉刷新
		// mContentLv.setMode(Mode.PULL_FROM_END);//只有上啦加载更多
		mContentAdapter = new ContentAdapter();
		mContent.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mContent.setAdapter(mContentAdapter);
		new GetUserDataAsync(pageIndex).execute();
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		findViewById(R.id.iv_back).setOnClickListener(this);
		
		mContentLv.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				pageIndex = 1;
				new GetUserDataAsync(pageIndex).execute();

			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {		
				new GetUserDataAsync(++pageIndex).execute();
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.iv_back:
			finish();
			break;
		}

	}		

	private class ContentAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mUserInfos.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mUserInfos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder = null;
			final PlayerInfo userInfo = mUserInfos.get(position);
			if (convertView == null) {
				convertView = LayoutInflater.from(SearchMoreUserActivity.this)
						.inflate(R.layout.search_more_user_activity_lay_item, null);
				holder = new PlaceHolder();
				holder.userHeadImg = (ImageView) convertView.findViewById(R.id.userHeadImg);
				holder.userName=(TextView)convertView.findViewById(R.id.userName);
				holder.fenshiCount=(TextView)convertView.findViewById(R.id.fenshiCount);
				holder.videoCount=(TextView)convertView.findViewById(R.id.videoCount);
				holder.layattention = (LinearLayout) convertView
						.findViewById(R.id.lay_attention);
				holder.ivAttention = (ImageView) convertView
						.findViewById(R.id.iv_attention);
				holder.tvAttention = (TextView) convertView
						.findViewById(R.id.tv_attention);
				convertView.setTag(holder);
			} else {
				holder = (PlaceHolder) convertView.getTag();
			}
			SetHead setHead = new SetHead();
			setHead.setHead(userInfo.getUserImg(), userInfo.getSex(), holder.userHeadImg);
			if(userInfo.getNickName() == null || userInfo.getNickName().equals("") || userInfo.getNickName().equals("null")){
				holder.userName.setText(userInfo.getUserName());
			}else{
				holder.userName.setText(userInfo.getNickName());
			}
			holder.fenshiCount.setText("粉丝："+userInfo.getFansCount());
			holder.videoCount.setText("视频："+userInfo.getVideoCount());
		
			final int pos = position;
			if(LoginInfo.getInstance().isLogin()){
				if(LoginInfo.getInstance().getUserId().equals(""+userInfo.getUserId())){
					holder.layattention.setVisibility(View.GONE);
				}
			}
			holder.layattention.setOnClickListener(new OnClickListener(){

	            @Override
	            public void onClick(View v) {
	                if (userInfo.getFocusType() == 1 || userInfo.getFocusType() == 2) {
	                    // info.setFocusOntype("0");
	                    // 如果未登录，就转到登录页面
	                    if (!LoginInfo.getInstance().isLogin()) {
	                        Intent login = new Intent();
	                        login.setClass(SearchMoreUserActivity.this, SettingLoginActivity.class);
	                        login.putExtra("loginFlag", 5);
	                        SearchMoreUserActivity.this.startActivityForResult(login, OptionSearchActivity.STATE_LOGIN);
	                    } else {
	                        // 如果登录则上传服务器:取消关注
	                        if (task == null) {
	                            task = new GetDataTask(LoginInfo.getInstance().getUserId(), ""+userInfo.getUserId(), "2", pos, 0);
	                            task.execute();
	                        } else if (task.getStatus() != Status.RUNNING) {
	                            task = new GetDataTask(LoginInfo.getInstance().getUserId(), ""+userInfo.getUserId(), "2", pos, 0);
	                            task.execute();
	                        } else {
	                            Logger.i(TAG, "正在上传服务器，请稍侯");
	                        }
	                    }
	                } else {
	                    // info.setFocusOntype("1");
	                    // 如果未登录，就转到登录页面
	                    if (!LoginInfo.getInstance().isLogin()) {
	                        Intent login = new Intent();
	                        login.setClass(SearchMoreUserActivity.this, SettingLoginActivity.class);
	                        login.putExtra("loginFlag", 2);
	                        SearchMoreUserActivity.this.startActivity(login);
	                    } else {
	                        // 如果登录则上传服务器:添加关注
	                        if (task == null) {
	                            task = new GetDataTask(LoginInfo.getInstance().getUserId(), ""+userInfo.getUserId(), "1", pos, 1);
	                            task.execute();
	                        } else if (task.getStatus() != Status.RUNNING) {
	                            task = new GetDataTask(LoginInfo.getInstance().getUserId(), ""+userInfo.getUserId(), "1", pos, 1);
	                            task.execute();
	                        } else {
	                            Logger.i(TAG, "正在上传服务器，请稍侯");
	                        }
	                    }
	                }
	                notifyDataSetChanged();
	            }
	        });
			if (userInfo.getFocusType() == 0 || userInfo.getFocusType() == 3) {
				holder.layattention.setBackgroundResource(R.drawable.icon_attention_bg_normal);
				holder.ivAttention.setVisibility(View.VISIBLE);
				holder.tvAttention.setText("关注");
	        } else if(userInfo.getFocusType() == 2){
	        	holder.layattention.setBackgroundResource(R.drawable.icon_attention_bg_press);
				holder.ivAttention.setVisibility(View.GONE);
				holder.tvAttention.setText("相互关注");
	        }else {
	        	holder.layattention.setBackgroundResource(R.drawable.icon_attention_bg_press);
				holder.ivAttention.setVisibility(View.GONE);
				holder.tvAttention.setText("已关注");
	        }
			convertView.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					if(LoginInfo.getInstance().isLogin()){
						if(LoginInfo.getInstance().getUserId().equals(""+userInfo.getUserId())){
//							Intent intent=new Intent(SearchMoreUserActivity.this,PersonalHomeActivity.class);
//							intent.putExtra("userId",""+userInfo.getUserId());
//							SearchMoreUserActivity.this.startActivity(intent);
						}else{
							Intent intent=new Intent(SearchMoreUserActivity.this,OtherPersonHomeActivity.class);
							intent.putExtra("userId",""+userInfo.getUserId());
							SearchMoreUserActivity.this.startActivity(intent);
						}
					}else{
						Intent intent=new Intent(SearchMoreUserActivity.this,OtherPersonHomeActivity.class);
						intent.putExtra("userId",""+userInfo.getUserId());
						SearchMoreUserActivity.this.startActivity(intent);
					}
				}});
			return convertView;
		}

		private class PlaceHolder {
			ImageView userHeadImg;
			TextView userName;
			TextView fenshiCount;
			TextView videoCount;
			LinearLayout layattention;
			ImageView ivAttention;
			TextView tvAttention;
		}

	}
	
	/**
	 * 根据关键词搜索用户数据
	 */
	private class GetUserDataAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		private ProgressDialog pd;
		private SearchUser2PageInfo userPageInfo;
		private int pageIndex;
		public GetUserDataAsync(int pageIndex) {
			this.pageIndex = pageIndex;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = Utils.getProgressDialog(SearchMoreUserActivity.this,
					getResources().getString(R.string.get_data), this);
			pd.show();
		}
		
		@Override
		protected void onCancelled() {
			if(mContentLv != null){
				mContentLv.onRefreshComplete();
			}
			super.onCancelled();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				SearchAboutUtil search = new SearchAboutUtil();
				userPageInfo = search.getUserBySearch(keyWord, ""+pageSize, ""+pageIndex);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
				if(mContentLv != null){
					Logger.i(TAG, "mContentLv下来结束刷新11111");
					mContentLv.onRefreshComplete();
				}
			}
			return false;

		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			Logger.i(TAG, "onPostExecute返回了");
			if (errorMsg.equals("")) {
				if(userPageInfo != null){
					if(userPageInfo.getObj() != null){
						SearchUser2Obj obj = userPageInfo.getObj();
						if(obj != null){
							SearchVideo2ObjInator inator = obj.getPaginator();
							if(inator != null && !isSetCount){
								isSetCount = true;
								int userCount = inator.getItems();
								String val=SearchMoreUserActivity.this.getResources().getString(
										R.string.search_more_user_title,keyWord,userCount);
								Utility.ChangeTextViewPartWordsTextColor(titleTxt, val,
										SearchMoreUserActivity.this.getResources().getColor(R.color.title_alpha_blue), 
										keyWord);
//								titleTxt.setText(val);
							}
						}
						if(obj.getList() != null){
							if(pageIndex == 1){
								mUserInfos.clear();
								mUserInfos.addAll(obj.getList());
							}else{
								mUserInfos.addAll(obj.getList());
							}
							if(obj.getList().size() < pageSize){
								mContentLv.setMode(Mode.PULL_UP_TO_REFRESH);
							}else{
								mContentLv.setMode(Mode.BOTH);
							}
							mContentAdapter.notifyDataSetChanged();
						}else{
//							mContentLv.setMode(Mode.PULL_DOWN_TO_REFRESH);
						}
					}else{
						ToastAlone
						.showToast(SearchMoreUserActivity.this, userPageInfo.getMsg(), 1);
					}
				}else{
					ToastAlone
					.showToast(SearchMoreUserActivity.this, "未知错误", 1);
				}
			} else {
				ToastAlone
						.showToast(SearchMoreUserActivity.this, errorMsg, 1);
			}
			if(mContentLv != null){
				mContentLv.onRefreshComplete();
			}else{
				Logger.i(TAG, "不知道为啥没有刷新");
			}
		}
	}
	
	GetDataTask task;
	private class GetDataTask extends AsyncTask<Object, Void, Void> {
        String userId = "";

        String focusUserId = "";
        SearchUpdataFocousInfo focousPageInfo;
        String typeId = "";

        int pos = 0;

        int attentionId = 0;
        private ProgressDialog pd;   
        public GetDataTask(String userId, String focusUserId, String typeId, int pos,
                int attentionId) {
            this.userId = userId;
            this.focusUserId = focusUserId;
            this.typeId = typeId;
            this.pos = pos;
            this.attentionId = attentionId;
        }

        int result = -1;
        
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = Utils.getProgressDialog(SearchMoreUserActivity.this, "正在加载数据...", this);
            pd.show();
        }

        @Override
        protected Void doInBackground(Object... params) {
            try {
                
                SearchAboutUtil searchUtil = new SearchAboutUtil();
                focousPageInfo = searchUtil.updataAttentionInfo1(userId, focusUserId, typeId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void reult) {
            Logger.i(TAG, "result=="+result);
            if (pd != null && pd.isShowing()) {
                pd.cancel();
            }
            if(focousPageInfo != null){
            	if(focousPageInfo.getResult().getCode().equals("0")){
//            		mUserInfos.get(pos).setFocusOntype(attentionId);
            		mUserInfos.get(pos).setFocusType(attentionId);
                    if(mContentAdapter != null)
                    {
                    	mContentAdapter.notifyDataSetChanged();
                    }
            	}else {
            		if(focousPageInfo.getResult().getMessage().contains("已关注")){
            			mUserInfos.get(pos).setFocusType(attentionId);
                        if(mContentAdapter != null)
                        {
                        	mContentAdapter.notifyDataSetChanged();
                        }
            		}
            	}
            }else{
            	ToastAlone.showToast(SearchMoreUserActivity.this,
						"网络异常，请稍后再试！", 1);
            }
//            if (result == 0) {// 取消或着关注成功
//                // 更新界面
//                mUserInfos.get(pos).setFocusOntype(attentionId);
//                if(mContentAdapter != null)
//                {
//                	mContentAdapter.notifyDataSetChanged();
//                }
//            }else {
//            	
////                infos.get(pos).setFocusOntype(attentionId);
////                notifyDataSetChanged();
//            }
        }
    }

}
